package com.wdd.myplatform.utils;

import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Set;

@ConditionalOnProperty(
        value = {"fdfs.enabled"},
        havingValue = "true",
        matchIfMissing = false
)
@Component
public class FdfsToolsUtil {
    private static Logger log = LoggerFactory.getLogger(FdfsToolsUtil.class);
    @Autowired
    private FastFileStorageClient storageClient;
    @Value("${fdfs.resHost}")
    private String resHost;

    public FdfsToolsUtil() {
    }

    public String uploadFile(MultipartFile file) throws Exception {
        StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), (Set)null);
        return this.getResAccessUrl(storePath);
    }

    public String uploadImage(BufferedImage bufferedImage, String imageExtension) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, imageExtension, os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        StorePath storePath = this.storageClient.uploadFile(input, (long)os.size(), imageExtension, (Set)null);
        return this.getResAccessUrl(storePath);
    }

    public String uploadFile(String filePath) throws Exception {
        File file = new File(filePath);
        StorePath storePath = this.storageClient.uploadFile(new FileInputStream(file), file.length(), FilenameUtils.getExtension(filePath), (Set)null);
        return this.getResAccessUrl(storePath);
    }

    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = this.storageClient.uploadFile(stream, (long)buff.length, fileExtension, (Set)null);
        return this.getResAccessUrl(storePath);
    }

    public String uploadFile(byte[] fileByteArray, String fileExtension) {
        ByteArrayInputStream stream = new ByteArrayInputStream(fileByteArray);
        StorePath storePath = this.storageClient.uploadFile(stream, (long)fileByteArray.length, fileExtension, (Set)null);
        return this.getResAccessUrl(storePath);
    }

    public byte[] downloadFile(String fileUrl) throws Exception {
        int index = fileUrl.indexOf("group");
        String groupUrl = fileUrl.substring(fileUrl.indexOf("group"));
        String group = groupUrl.substring(0, fileUrl.indexOf("/") + (index > 0 ? 1 : 0));
        String path = groupUrl.substring(fileUrl.indexOf("/") + (index > 0 ? 2 : 1));
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = (byte[])this.storageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }

    public FileInfo getFile(String groupName, String path) {
        FileInfo fileInfo = null;
        log.info("文件信息入参，groupName:{}，path:{}", groupName, path);

        try {
            fileInfo = this.storageClient.queryFileInfo(groupName, path);
            log.info("文件信息:{}", fileInfo.toString());
        } catch (Exception var5) {
            log.error("Non IO Exception: Get File from Fast DFS failed", var5);
        }

        return fileInfo;
    }

    public String uploadImageAndCrtThumbImage(MultipartFile file) throws Exception {
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), (Set)null);
        return this.getResAccessUrl(storePath);
    }

    public void deleteFile(String fileUrl) {
        if (null != fileUrl && !"".equals(fileUrl)) {
            try {
                StorePath storePath = StorePath.parseFromUrl(fileUrl);
                this.storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
            } catch (Exception var3) {
                log.error(var3.getMessage());
            }

        }
    }

    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = this.resHost + "/" + storePath.getFullPath();
        return fileUrl;
    }

    public static void main(String[] args) {
        String fileUrl = "group1/M00/00/00/wKhnymELkZGAYe3NAAABG6VUfqA418.png";
        System.out.println(fileUrl.indexOf("group"));
        String groupUrl = fileUrl.substring(fileUrl.indexOf("group"));
        String group = groupUrl.substring(0, fileUrl.indexOf("/") + 1);
        String path = groupUrl.substring(fileUrl.indexOf("/") + 2);
        System.out.println(groupUrl);
        System.out.println(group);
        System.out.println(path);
    }
}
